import { Button, message, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import $utils from '@/utils/utils';

import { whiteListStatusData } from '@/utils/common';
import { getPickupFreeList, pickupFreeDelete, pickupFreeDisable, pickupFreeEnable } from '@/services/pickUpWhiteList';

const initDate = {};
const userInfo = $utils.getStorage('user_info');

const PickUpWhiteList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);

    const l_state: any = history.location.state;
    useEffect(() => {

        if (!initParams) {
            const data = {
                ...l_state,
                ...initDate,
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
        }
        if (JSON.stringify(initParams) === JSON.stringify(data)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    // 删除弹窗
    const del_confirm = (id: number) => {
        Modal.confirm({
            title: '删除',
            content: '确定是否要删除',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除通知
                const msg = await pickupFreeDelete({ pickupFreeId: id, name: userInfo.name });
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    // 禁用启用弹窗
    const updStatus_confirm = (id: number, status: number) => {
        Modal.confirm({
            title: status === 1 ? '禁用' : '启用',
            content: status === 1 ? '确定是否要禁用' : '确认是否启用',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const params = {
                    pickupFreeId: id,
                    name: userInfo.name
                }
                let msg = null;
                if (status === 1) {
                    msg = await pickupFreeDisable(params);
                } else {
                    msg = await pickupFreeEnable(params);
                }
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    const columns: ProColumns<any>[] = [
        {
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            title: '有效时间',
            dataIndex: 'effectiveTime',
            search: false,
            hideInForm: true,
            width: 180,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            fieldProps: {
                options: whiteListStatusData,
            },
            width: 80,
            render: (dom: any, record: any) => {
                return (<div style={{ color: record.status === 1 ? 'green' : 'red' }}>{dom}</div>)
            }
        },
        {
            title: '备注',
            dataIndex: 'note',
            search: false,
            width: 100,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
            width: 120,
        },
        {
            title: '创建人',
            dataIndex: 'createUserName',
            search: false,
            hideInForm: true,
            width: 120,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            search: false,
            hideInForm: true,
            width: 120,
        },
        {
            title: '修改人',
            dataIndex: 'updateUserName',
            search: false,
            hideInForm: true,
            width: 120,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Access accessible={true}>
                        <Button type="primary" size="small" onClick={() => {
                            const newTab = {
                                name: `编辑${record.phone}取件白名单详情`,
                                path: '/BusinessConfig/PickUpWhiteList/detail',
                                state: {
                                    status: 'update',
                                    data: record
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BusinessConfig/PickUpWhiteList/detail',
                                state: {
                                    status: 'update',
                                    data: record
                                }
                            });
                        }}>编辑</Button>
                    </Access>
                    {/* <Button type="primary" size="small" onClick={() => {
                        updStatus_confirm(record.id, record.status)
                    }}>{record.status === 1 ? '禁用' : '启用'}</Button> */}
                    <Button type="primary" size="small" danger onClick={() => {
                        del_confirm(record.id);
                    }}>删除</Button>
                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                formRef={formRef}
                form={{
                    initialValues: initParams
                }}
                search={true ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: 6,
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                const data = {
                                    ...initDate,
                                };
                                setParams(data);
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                options={false}
                title={() => [
                    <Access key="index" accessible={true}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `添加取件白名单`,
                                path: '/BusinessConfig/PickUpWhiteList/detail',
                                state: {
                                    status: 'create'
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BusinessConfig/PickUpWhiteList/detail',
                                state: {
                                    status: 'create'
                                }
                            });
                        }}>批量添加</Button>
                    </Access>
                ]}
                params={{ stationId: userInfo.stationId }}
                request={async (params: any) => {
                    const msg = await getPickupFreeList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '取件白名单',
                            path: '/BusinessConfig/PickUpWhiteList',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default PickUpWhiteList;
